package com.frank.httpdemo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.entity.InputStreamEntity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.frank.http.base.AsyncHttpClient;
import com.frank.http.base.AsyncHttpResponseHandler;
import com.frank.http.base.RequestParams;
import com.frank.http.encryp.HttpHeader;
import com.frank.http.expand.ACache;
import com.frank.http.expand.CacheAsyncHttpClient;
import com.frank.http.expand.CacheAsyncHttpResponseHandler;
import com.frank.http.expand.InitUitls;
import com.frank.http.expand.LocalEncryption;
import com.frank.http.expand.Logger;
import com.frank.http.expand.PreferenceAppService;
import com.google.gson.Gson;

public class MainActivity extends ActionBarActivity implements OnClickListener {
	private final static String TAG = MainActivity.class.getSimpleName();
	private Context context;
	private TextView d;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		context = this;
		LocalEncryption.createKey(context);
		// d = (TextView) this.findViewById(R.id.d);
		// d.setOnClickListener(this);
		PreferenceAppService.init(this);
		// KeyGenerator keyGenerator = null;
		// try {
		// keyGenerator = KeyGenerator.getInstance("AES");
		// } catch (NoSuchAlgorithmException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// keyGenerator.init(256);
		// SecretKey secretKey = keyGenerator.generateKey();
		// byte[] keyBytes = secretKey.getEncoded();

		// KeyGenerator desKeyGenerator = null;
		// try {
		// desKeyGenerator = KeyGenerator.getInstance("DESede");
		// } catch (NoSuchAlgorithmException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		// desKeyGenerator.init(168);
		// SecretKey desSecretKey = desKeyGenerator.generateKey();
		// byte[] bytesKey = desSecretKey.getEncoded();
		// InitUitls.initSession(context,
		// "http://test22.api.xsw0306.com/session/init");
		// InitUitls.setInitSessionUrl("http://api.qfx.ping-qu.com/session/init");
		// InitUitls.initSession(context,
		// "http://api.qfx.ping-qu.com/session/init");
		// InitUitls.setInitSessionUrl("http://10.1.1.20:8088/session/init");
		// InitUitls.initSession(context,
		// "http://10.1.1.20:8088/session/init");
		// InitUitls
		// .setInitSessionUrl("http://zhongqitest3.ping-qu.com/session/init");
		// InitUitls.initSession(context,
		// "http://zhongqitest3.ping-qu.com/session/init");
		InitUitls.setInitSessionUrl("http://api.qfx.ping-qu.com/session/init");
		InitUitls.initSession(context,
				"http://api.qfx.ping-qu.com/session/init");
		initTest7();
		// initTest5();
		// initTest3();
		// Gson gson = new Gson();
		// String a = "";
		// String b = gson.toJson(a);
		// String c = gson.fromJson(b, String.class);
		// Logger.i(TAG, b);
		// Logger.i(TAG, c);
		// Logger.i(TAG, "session_id_name:"
		// + PreferenceAppService.getInstance().getItem("session_id_name"));
		// Logger.i(
		// TAG,
		// "session_id_name:"
		// + PreferenceAppService.getInstance().getItem(
		// "session_card_name"));
		// Logger.i(TAG, "session_key_name:"
		// + PreferenceAppService.getInstance()
		// .getItem("session_key_name"));
		// Logger.i(TAG, "session_key_name:"
		// + PreferenceAppService.getInstance()
		// .getItem("session_key_name"));
		// Logger.i(
		// TAG,
		// "session_sign_name:"
		// + PreferenceAppService.getInstance().getItem(
		// "session_sign_name"));
		// Logger.i(TAG, "session_prefix:"
		// + PreferenceAppService.getInstance().getItem("session_prefix"));
		// Logger.i(TAG, "session_id:"
		// + PreferenceAppService.getInstance().getItem("session_id"));
		// Logger.i(TAG, "session_card:"
		// + PreferenceAppService.getInstance().getItem("session_card"));
		// Logger.i(TAG, "session_key:"
		// + PreferenceAppService.getInstance().getItem("session_key"));
		// Logger.i(TAG, "session_sign:"
		// + PreferenceAppService.getInstance().getItem("session_sign"));

		// initTest3();
	}

	private void initTest6() {
		// CacheAsyncHttpClient client = new CacheAsyncHttpClient(
		// new AsyncHttpClient(), context);
		// String url =
		// "http://api.qfx.ping-qu.com/v1_0/app/goods/goods_info?goods_id=10000046";
		AsyncHttpClient client = new AsyncHttpClient();

		String url = "http://api.qfx.ping-qu.com/v1_0/app/homepage";

		RequestParams parameters = new RequestParams();
		parameters.put("article_id", "152");
		String pa = "article_id=152";

		Log.i("parameters", parameters.toString());
		client.delete(url, parameters, new AsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					byte[] responseBody) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					byte[] responseBody, Throwable error) {
				// TODO Auto-generated method stub

			}
		}, true);

	}

	private void initTest5() {
		CacheAsyncHttpClient client = new CacheAsyncHttpClient(
				new AsyncHttpClient(), context);
		String url = "http://zhongqitest3.ping-qu.com/Api/Article/recommendList";
		ArrayList<ArrayList<String>> arrayList = new ArrayList<ArrayList<String>>();
		ArrayList<String> arrayList2 = new ArrayList<String>();
		arrayList2.add("asdfasd");
		arrayList2.add("asdfasdsdf");
		arrayList.add(arrayList2);

		ArrayList<Map<String, String>> arraylistMap = new ArrayList<Map<String, String>>();
		Map<String, String> map = new HashMap<String, String>();
		map.put("S", "sfsd");
		arraylistMap.add(map);
		RequestParams parameters = new RequestParams();
		parameters.put("a", "a");
		parameters.put("arrayList", arrayList);
		parameters.put("arraylistMap", arraylistMap);
		ACache aCache = ACache.get(getDefaultSavePath());
		client.setAcache(aCache);
		Log.i("parameters", parameters.toString());
		client.put(url, parameters, new CacheAsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode,
					org.apache.http.Header[] headers, byte[] responseBody) {
				String string = new String(responseBody);
				Logger.i(TAG, "string:" + string);

			}

			@Override
			public void onFailure(int statusCode,
					org.apache.http.Header[] headers, byte[] responseBody,
					Throwable error) {
				// TODO Auto-generated method stub

			}
		}, true);

	}

	/**
	 * 默认缓存网络数据路径
	 * 
	 * @return
	 */
	public static File getDefaultSavePath() {
		String path = Environment.getExternalStorageDirectory()
				+ File.separator + "httpDemo";
		File dcp = null;
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			dcp = new File(path);
			if (!dcp.exists()) {
				dcp.mkdirs();
				return dcp;
			}
		}
		return dcp;
	}

	private void initTest4() {
		CacheAsyncHttpClient client = new CacheAsyncHttpClient(
				new AsyncHttpClient(), context);
		String url = "http://api.qfx.ping-qu.com/v1_0/app/dynamic/shoparticle";
		// String url =
		// "http://test22.api.xsw0306.com/project_2_0/subject_recom/get_cate_curri";

		String appid = "wxd930ea\"5d5a258f4f";
		String mch_id = "10000100";
		String device_info = "1000";
		String body = "test";
		String nonce_str = "ibuaiVcKdpRxkhJA";
		String test1 = "~._-*";
		String test4 = "!@#$%^&()+{}";
		String test2 = "\"\\/``";
		String test3 = ":|<>,?[];'";
		ArrayList<String> arrayList = new ArrayList<String>();
		arrayList.add("s234dfsa");
		arrayList.add("sdfs234a");
		arrayList.add("s23423dfsa");

		RequestParams parameters = new RequestParams();
		// parameters.put("appid", appid);
		// parameters.put("mch_id", mch_id);
		// parameters.put("device_info", device_info);
		// parameters.put("body", body);
		// parameters.put("nonce_str", nonce_str);
		// parameters.put("da", "");
		// parameters.put("test1", test1);
		// parameters.put("test4", test4);
		// parameters.put("test2", test2);
		// parameters.put("test3", test3);

		Log.i("parameters", parameters.toString());
		client.get(url, parameters, new CacheAsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode,
					org.apache.http.Header[] headers, byte[] responseBody) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onFailure(int statusCode,
					org.apache.http.Header[] headers, byte[] responseBody,
					Throwable error) {
				// TODO Auto-generated method stub

			}
		}, true);
		// client.post(url, parameters, new CacheAsyncHttpResponseHandler() {
		//
		// @Override
		// public void onSuccess(int statusCode,
		// org.apache.http.Header[] headers, byte[] responseBody) {
		// // TODO Auto-generated method stub
		//
		// }
		//
		// @Override
		// public void onFailure(int statusCode,
		// org.apache.http.Header[] headers, byte[] responseBody,
		// Throwable error) {
		// // TODO Auto-generated method stub
		//
		// }
		// }, true);
	}

	private void initTest2() {
		CacheAsyncHttpClient client = new CacheAsyncHttpClient(
				new AsyncHttpClient(), context);
		// String url =
		// "http://test22.api.xsw0306.com/project_2_0/subject_recom/get_cate_curri?te=12&td=d&adc=sf&dsfds=adfdsew";
		String url = "http://10.1.1.20:8088/v1_0/app/brand_story?te=12&td=d&adc=sf&dsfds=adfdsew";
		String appid = "wxd930ea\"5d5a258f4f";
		String mch_id = "10000100";
		String device_info = "1000";
		String body = "test";
		String nonce_str = "ibuaiVcKdpRxkhJA";
		String test1 = "~._-*";
		String test4 = "!@#$%^&()+{}";
		String test2 = "\"\\/``";
		String test3 = ":|<>,?[];'";
		ArrayList<String> arrayList = new ArrayList<String>();
		arrayList.add("s234dfsa");
		arrayList.add("sdfs234a");
		arrayList.add("s23423dfsa");

		RequestParams parameters = new RequestParams();
		parameters.put("appid", appid);
		parameters.put("mch_id", mch_id);
		parameters.put("device_info", device_info);
		parameters.put("body", body);
		parameters.put("nonce_str", nonce_str);
		parameters.put("da", "");
		parameters.put("test1", test1);
		parameters.put("test4", test4);
		parameters.put("test2", test2);
		parameters.put("test3", test3);
		parameters.put("arrayList", arrayList);
		try {
			// parameters.put("file", new File("/storage/emulated/0/test.txt"));
			// parameters
			// .put("file1", new File("/storage/emulated/0/content.txt"));
			parameters.put("file1", new File("/storage/emulated/0/test.jpg"));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// parameters.put("dad", "{\"da\":\"dd\",\"ddf\":\"真的\"}");
		// parameters
		// .put("dad2",
		// "http://file.cdnbos.bce.xsw0306.com/user/moments_img/1417_49972b6087d06f89.jpg");
		parameters
				.put("test",
						"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~._-*!@#$%^&()+{}:|<>,?=[];'\"\\/``");

		Log.i("parameters", parameters.toString());
		client.post(url, parameters, new CacheAsyncHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode,
					org.apache.http.Header[] headers, byte[] responseBody) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onFailure(int statusCode,
					org.apache.http.Header[] headers, byte[] responseBody,
					Throwable error) {
				// TODO Auto-generated method stub

			}
		}, true);
	}

	private void initTest3() {
		AsyncHttpClient client = new AsyncHttpClient();
		String url = "http://api.qfx.ping-qu.com/v1_0/test/cs/dump";

		Test test = new Test("da", "dads", "dda", "ddserra");
		Gson gson = new Gson();
		String data = gson.toJson(test);

		byte[] b = data.getBytes();
		InputStream instream = null;
		instream = new ByteArrayInputStream(b);
		HttpEntity entity = new InputStreamEntity(instream, b.length);

		ByteArrayOutputStream os = new ByteArrayOutputStream();
		InputStream is = new ByteArrayInputStream(b);
		int bytes = -1;
		try {
			while ((bytes = is.read()) != -1) {
				os.write(bytes);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		client.post(context, url, entity, os, null,
				new AsyncHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							byte[] responseBody) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] responseBody, Throwable error) {
						// TODO Auto-generated method stub

					}
				}, true, 1);

	}

	private void initTest7() {
		AsyncHttpClient client = new AsyncHttpClient();
		String url = "http://api.qfx.ping-qu.com/v1_0/app/homepage";

		String data = "article_id=152&test=22";

		byte[] b = data.getBytes();
		InputStream instream = null;
		instream = new ByteArrayInputStream(b);
		HttpEntity entity = new InputStreamEntity(instream, b.length);

		ByteArrayOutputStream os = new ByteArrayOutputStream();
		InputStream is = new ByteArrayInputStream(b);
		int bytes = -1;
		try {
			while ((bytes = is.read()) != -1) {
				os.write(bytes);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		client.delete(context, url, entity, os, null,
				new AsyncHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							byte[] responseBody) {

					}

					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] responseBody, Throwable error) {

					}
				}, true, 2);

	}

	@Override
	public void onClick(View v) {
		Intent intent = new Intent();
		intent.setClass(context, MainActivity1.class);
		Bundle bundle = new Bundle();
		intent.putExtras(bundle);
		context.startActivity(intent);
	}

}
